/**  
 * @Title: AppSendUtils.java
 * @Package org.csun.bt.utils.map
 * @Description: TODO
 * @author chisj chisj@foxmail.com
 * @date 2017年12月7日
 */
package com.csun.cmny.provider.utils.map;

import com.csun.cmny.util.PublicUtil;
import com.google.gson.Gson;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * ClassName: AppSendUtils 
 * @Description: 百度地图工具类
 * @author chisj chisj@foxmail.com
 * @date 2017年12月7日
 */
public class BaiduMapUtils {  
	
	// 百度ak
	private static final String ak = "oEMUk2R653OdTdUhW6PgSrO0CGOOYG4N";
	
	private static final String LBS_WIFI_URL = "http://api5.mini361.com/wifi.aspx";
	
    private static final Logger Log = LoggerFactory.getLogger(BaiduMapUtils.class);
    
    /**
     * @Description: 计算两个点之间的距离
     * @param startPoint 起点  lat,lng
     * @param endPoint 终点 lat,lng
     * @param @return   
     * @return int  
     * @throws
     * @author chisj chisj@foxmail.com
     * @date 2018年9月3日
     */
    public static int getDistanceByPoints(String startPoint, String endPoint) {
    	
    	int ret = -1;

    	//拼接计算两点驾车距离的百度API接口
//    	String url =  String.format("http://api.map.baidu.com/routematrix/v2/driving?"+
//    			"output=json&origins=" + Double.parseDouble(StringUtil.convertMapString(startPoint, "lat"))+
//    	"," + Double.parseDouble(StringUtil.convertMapString(startPoint, "lng"))+
//    	"&destinations="+Double.parseDouble(StringUtil.convertMapString(endPointMap, "lat"))+
//    	"," + Double.parseDouble(StringUtil.convertMapString(endPointMap, "lng"))+
//    	"&ak=" + ak);
    	
    	String url = "http://api.map.baidu.com/routematrix/v2/walking?output=json&origins="
    				+ startPoint 
    				+ "&destinations="
    				+ endPoint
    				+ "&ak=" + ak;
    	
    	String json = loadJSON(url);
    	
    	//将返回结果转换成map
    	Map<String, Object> reMap = JsonUtil.getMap4Json(json);
    	System.out.println("reMap = " + reMap);
    	
    	Map<String, Object> resultMap = (Map) ((List) (reMap.get("result"))).get(0);
	    Map<String, Object> disMap = (Map)resultMap.get("distance");
	    
	    System.out.println("value = " + disMap.get("value"));
    	
    	return ret;
    }
    
    /**
	* @Title: loadJSON
	* @Description: 得到请求返回结果
	* @param url 百度API请求地址
	* @return 返回String雷锤
	*/
	public static String loadJSON (String url) {  
	          StringBuilder json = new StringBuilder();  
	          try {  
	              URL oracle = new URL(url);  
	              URLConnection yc = oracle.openConnection();  
	              BufferedReader in = new BufferedReader(new InputStreamReader(  
	                                          yc.getInputStream()));  
	              String inputLine = null;  
	              while ( (inputLine = in.readLine()) != null) {  
	                  json.append(inputLine);  
	              }  
	              in.close();  
	          } catch (MalformedURLException e) {  
	         e.printStackTrace();
	          } catch (IOException e) {  
	         e.printStackTrace();
	          }  
	          return json.toString();  
	      }  
    
    public static String connectURL(String dest_url, String commString) {  
        String rec_string = "";  
        URL url = null;  
        HttpURLConnection urlconn = null;  
        OutputStream out = null;  
        BufferedReader rd = null;  
        try {  
            url = new URL(dest_url);
            System.out.println("url:"+url);
            urlconn = (HttpURLConnection) url.openConnection();  
            urlconn.setReadTimeout(1000 * 30);  
            //urlconn.setRequestProperty("content-type", "text/html;charset=UTF-8");  
            urlconn.setRequestMethod("POST");  
            urlconn.setDoInput(true);   
            urlconn.setDoOutput(true);  
            out = urlconn.getOutputStream();  
            out.write(commString.getBytes("UTF-8"));  
            out.flush();   
            out.close();  
            rd = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));  
            StringBuffer sb = new StringBuffer();  
            int ch;  
            while ((ch = rd.read()) > -1)  
                sb.append((char) ch);  
            rec_string = sb.toString();  
        } catch (Exception e) {  
            Log.error(e.toString(), e);  
            return "";  
        } finally {  
            try {  
                if (out != null) {  
                    out.close();  
                }  
                if (urlconn != null) {  
                    urlconn.disconnect();  
                }  
                if (rd != null) {  
                    rd.close();  
                }  
            } catch (Exception e) {  
                Log.error(e.toString(), e);  
            }  
        }  
        return rec_string;  
    }  
  
    public static void main(String[] args) {  
        //String coords = "106.6519570767,26.6245856997";  
    	//String coords = "114.39960787,30.47750785";
        //String result =connectURL("http://api.map.baidu.com/geoconv/v1/?coords="+coords+"&from=1&to=5&output=json&ak=oEMUk2R653OdTdUhW6PgSrO0CGOOYG4N","");  
        // 125.48276|37.615124
    	//String result = gpsGetLocation("3028.650471N,11423.976472E");
    	//String result = gpsGetLocation("3048.04950428N,11441.13999870E");
    	//String result = gpsGetLocation("3146.581073N,11705.129662E");
//    	String result = gpsConvertFormat("");
//    	System.out.println(result);
//    	String ret = "";
//    	
//    	ret = gpsCoverLbsWifi(460,1,"7138,38581,55|7138,38583,44|7138,38582,37|7138,55173,17|");
//    	ret = gpsGetLocation(ret);
//    	System.out.println("ret = " + ret);
//    	ret = gpsCoverLbsWifi(460,1,"7138,38581,55|7138,38583,44|7138,38582,37|7138,55173,17|", "test,f4:83:cd:21:29:3f,-46|test,6c:b7:49:76:8f:bc,-89|test,28:6c:07:97:c9:db,-90|test,9c:6f:52:3e:fe:21,-91|test,dc:fe:18:dc:b7:9b,-92|test,b0:d5:9d:cf:e4:5a,-93|");
//    	ret = gpsGetLocation(ret);
//    	System.out.println("ret = " + ret);
    	//getLbsWifiLocation();
    	
//    	startPointMap.put("lng", "114.4291917726292");
//    	startPointMap.put("lat", "30.418032456341848");
//    	
//    	endPointMap.put("lng", "114.42473839917815");
//    	endPointMap.put("lat", "30.420710098164225");
    	
//    	String startPoint = "30.418032456341848,114.4291917726292";
//    	String endPoint = "30.420710098164225,114.42473839917815";
//
//    	getDistanceByPoints(startPoint, endPoint);

		String ret = connectURL("http://api.cellocation.com:81/loc/?wl=56:56:3b:00:b4:1b,-57;00:87:46:22:1d:4a,-78;9c:a6:15:fb:ba:51,-80;54:75:95:d4:93:c0,-93;00:22:aa:d6:8d:9a,-63;34:46:ec:89:f7:29,-94;8c:21:0a:5f:53:60,-80&output=json\n", "");

		Map map = JSONObject.fromObject(ret);
		String lat = (String) map.get("lat");
		String lon = (String) map.get("lon");
		System.out.println("lat = " + lat + ", lon = " + lon);

		System.out.println("ret = " + ret);
    }  
    
    public static void getLbsWifiLocation() {
    	
    	String str = "@B#@|01|001|864891030238945|9460012796626210|1|15|"
    			+ "20180813023253|f4:83:cd:21:29:3f,-46&6c:b7:49:76:8f:bc,"
    			+ "-89&28:6c:07:97:c9:db,-90&9c:6f:52:3e:fe:21,-91&dc:fe:18:dc:b7:9b,"
    			+ "-92&b0:d5:9d:cf:e4:5a,-93|38581,7138,1,460,55&38583,7138,1,460,44&38582,"
    			+ "7138,1,460,37&55173,7138,1,460,17|3|@E#@";
    	
    	String [] Items = str.split("@E#@@B#@");
    	
    	String cmdStr = "";
    	cmdStr = "@B#@" +Items[0].replace("@E#@", "").replace("@B#@", "")+ "@E#@";
    	
    	String[] data = cmdStr.split("\\|");
    	
    	String protocol = data[2];
    	int length = data.length;
    	if (protocol.equals("001")) {
    		String isGps = data[length - 2]; // 定位类型
    		if (isGps.equals("3")) {
    			String mcc = "0";
    			String mnc = "0";
    			String[] wifiInfos = data[8].split("&");
    			String wifiInfo = "";
    			String lbsMore = "";
    			for (int i = 0; i < wifiInfos.length; i++)
                {
                    String wifi[] = wifiInfos[i].split(",");
                    String mac = wifi[0];
                    String db = wifi[1];
                    wifiInfo += "test," + mac + "," + db + "|";
                }
//    			wifiInfo = wifiInfo.
    			System.out.println("wifiInfo = " + wifiInfo);
    			String lbsInfos[] = data[9].split("&");
    			for (int i = 0; i < lbsInfos.length; i++)
                {
                    String[] lbsInfo = lbsInfos[i].split(",");
                    String cid = lbsInfo[0];
                    String lac = lbsInfo[1];
                    if (mcc.equals("0") & mnc.equals("0"))
                    {
                        mnc = lbsInfo[2];
                        mcc = lbsInfo[3];
                    }
                    String db = lbsInfo[4];
                    lbsMore = lbsMore + lac + "," + cid + "," + db + "|";
//                    if (cid != 0 && lac != 0 && db != 0)
//                    {
//                        var cell = new CellInfo()
//                        {
//                            Lac = lac,
//                            Cid = cid,
//                            Db = db
//                        };
//                        lbsMore = lbsMore + cell.Lac + "," + cell.Cid + "," + cell.Db + "|";
//                        liCell.Add(cell);
//                    }
                    System.out.println("lbsMore = " + lbsMore);
                }
    			
    			String param = "mcc=" + mcc + "&mnc=" + mnc + "&cells=" 
    						+ lbsMore.substring(0, lbsMore.length() - 1) 
    						+ "&wifi=" + wifiInfo.substring(0, wifiInfo.length() - 1) 
    						+ "&key=9KD84JGH382JF1O";
    			System.out.println("param = " + param);
    		}
    	}
    	
    }
    
//    public static void main(String[] args) {
//    	
//    	String latitude = "3028.650471";
//    	
//    	int degrees = (int)Double.parseDouble(latitude.trim()) / 100; 
//    	
//    	System.out.println("degrees= " + degrees);
//    	
//    	double minutes = Double.parseDouble(latitude.trim()) - (degrees * 100);
//    	
//    	System.out.println("minutes= " + minutes);
//    	
//    	double result = degrees + (minutes / 60.0);
//    	
//    	System.out.println("result= " + (float)result);
//    	
//    }
    
    /**
     * 
     * @Description: 纬度ddmm.mmmm 转 纬度dd.dddddd 经度dddmm.mmmm 转 经度ddd.dddddd
     * @param ref 方向,默认为N(北),E(东),可以指定S(南),W(西)
     * @param @return   
     * @return float  
     * @throws
     * @author chisj chisj@foxmail.com
     * @date 2017年12月7日
     */
    private static float convertRationalLatLonToFloat(
            String rationalString, String ref) {
    	double result = 0.0;
    	try {
    		
    		int degrees = (int)Double.parseDouble(rationalString.trim()) / 100; 
    		
        	double minutes = Double.parseDouble(rationalString.trim()) - (degrees * 100);
        	
        	result = degrees + (minutes / 60.0);
        	
        	if (ref.equals("S") || ref.equals("W")) {
        		return (float) -result;
        	}
        	
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	System.out.println("result = " + result);
    	return (float)result;
    }
    
    /**
     * @Description: 转换GPRS经度、纬度为十进制
     * @param location 需要转换的GPRS坐标(3028.650471N,11423.976472E)
     * @return String 转换后的GPRS坐标()
     * @throws
     * @author chisj chisj@foxmail.com
     * @date 2017年12月7日
     */
    public static String gpsConvertFormat(String location) {
    	// 通过‘,’切分经纬度
    	//String array[] = location.split(",");
    	// 获取纬度
    	//int length = array[0].length();
    	//float latitude = convertRationalLatLonToFloat(array[0].substring(0, length - 2), array[0].substring(length - 2, length - 1));
    	//float latitude = convertRationalLatLonToFloat(array[0].substring(0, length - 2), array[0].substring(length - 2, length - 1));

    	// 获取经度
    	//float longitude = convertRationalLatLonToFloat(array[1].substring(0, length - 2), array[1].substring(length - 2, length - 1));
    	//float longitude = convertRationalLatLonToFloat(array[1].substring(0, length - 2), array[1].substring(length - 2, length - 1));;
    	
    	//String coords = String.valueOf(longitude) + "," + String.valueOf(latitude);
    	String coords = "30.4776167040595,114.399424903973";

    	String result = connectURL("http://api.map.baidu.com/geoconv/v1/?coords="+coords+"&from=1&to=5&output=json&ak=oEMUk2R653OdTdUhW6PgSrO0CGOOYG4N","");
    	System.out.println("result = " + result);
    	Gson gson = new Gson();
    	BaiduResult baidiResult = gson.fromJson(result, BaiduResult.class);
    	
    	if (baidiResult.getStatus() != 0) {
    		return null;
    	}
    	
    	return baidiResult.getResult().get(0).toString();
    }

    /**
     * @Description: 根据GPRS坐标查询位置、纬度为十进制
     * @param location GPRS坐标(3028.650471N,11423.976472E)
     * @throws
     * @author puyijun
     * @date 2018年01月18日
     */
    public static String gpsGetLocation(String location) {
        // 通过‘,’切分经纬度
//        String array[] = location.split(",");
        // 获取纬度
//        int length = array[0].length();
//        float latitude = convertRationalLatLonToFloat(array[0].substring(0, length - 2), array[0].substring(length - 2, length - 1));

        // 获取经度
//        float longitude = convertRationalLatLonToFloat(array[1].substring(0, length - 2), array[1].substring(length - 2, length - 1));;


//        String coords = String.valueOf(latitude) + "," + String.valueOf(longitude);

        String result = connectURL("http://api.map.baidu.com/geocoder/v2/?location="+location+"&coordtype="+"wgs84ll"+"&output=json&ak=oEMUk2R653OdTdUhW6PgSrO0CGOOYG4N","");
        Gson gson = new Gson();
        MapLocation baidiResult = gson.fromJson(result, MapLocation.class);
        if (baidiResult.getStatus() != 0) {
            return null;
        }
        // lat,lng&formatted/sematic
        return baidiResult.getResult().getLocation().getLat() 
        		+ "," + baidiResult.getResult().getLocation().getLng() 
        		+ "&" + baidiResult.getResult().getFormatted_address() 
        		+ "/" + baidiResult.getResult().getSematic_description();

    }
    
    
    public String convertBaidu(String coords) {
    	
    	return connectURL("http://api.map.baidu.com/geoconv/v1/?coords="+coords+"&from=1&to=5&output=json&ak=oEMUk2R653OdTdUhW6PgSrO0CGOOYG4N","");
    	
    }

	/**
	 * @Description: 将ddd.mmmmm<>,dd.mmmmm
	 * @param @param gpsString
	 * @param @return   
	 * @return String  
	 * @throws
	 * @author chisj chisj@foxmail.com
	 * @date 2018年8月14日
	 */
	public static String gpsCoverMin2Degree(String gpsString) {
		// TODO Auto-generated method stub
		return null;
	}


	public static String gpsByLbsWifi(String cl, String wl) {

		// http://www.cellocation.com/api/
		// http://api.cellocation.com:81/loc/
		String url = "http://api.cellocation.com:81/loc/?output=json";
		if (PublicUtil.isNotEmpty(cl)) {
			url = url + "&cl=" + cl.substring(0, cl.length() - 1);
		}
		if (PublicUtil.isNotEmpty(wl)) {
			url = url + "&wl=" + wl.substring(0, wl.length() - 1);
		}

//		String param = "?mcc=" + mcc + "&mnc=" + mnc
//				+ "&cells=" + lbsInfo.substring(0, lbsInfo.length() - 1)
//				+ "&wifi=" + wifiInfo.substring(0, wifiInfo.length() - 1)
//				+ "&key=9KD84JGH382JF1O";
		String ret = connectURL(url, "");

		System.out.println("====> chisj url = " + url + ", ret = " + ret);

//		String ret = connectURL("http://api.cellocation.com:81/loc/?wl=56:56:3b:00:b4:1b,-57;00:87:46:22:1d:4a,-78;9c:a6:15:fb:ba:51,-80;54:75:95:d4:93:c0,-93;00:22:aa:d6:8d:9a,-63;34:46:ec:89:f7:29,-94;8c:21:0a:5f:53:60,-80&output=json\n", "");

		Map map = JSONObject.fromObject(ret);
		String lat = (String) map.get("lat");
		String lon = (String) map.get("lon");
		System.out.println("lat = " + lat + ", lon = " + lon);

//		String[] gps = ret.split(",");

		return lat + "," + lon;
	}

	/**
	 * @Description: 根据基站/WIFI获取GPS定位数据
	 * @param mcc 移动国家号码
	 * @param mnc 移动网络号码
	 * mcc mnc
	 * 460 00, “CHINA MOBILE”, “CN” 中国移动TD 
	 * 460 01, “CHN-CUGSM”, “CN” 中国联通 
	 * 460 02, “CHINA MOBILE”, “CN” 中国移动GSM 
	 * 460 03, “CHINA TELECOM”, “CN” 中国电信CDMA
	 * @param lbsInfo 基站数据 
//	 * @param lac location area code 地区区域码, 用来划分区域
//	 * @param cell_Id cell tower id 代表一个移动基站
//	 * @param rssi received signal strength indication 接收信号强度指示
	 * lac  cid  db(rssi)
	 * 
	 * @param @return   
	 * @return String 返回的经纬度(lat,lng) 
	 * @throws
	 * @author chisj chisj@foxmail.com
	 * @date 2018年8月14日
	 */
	public static String gpsCoverLbsWifi(int mcc, int mnc, String lbsInfo) {
		// TODO Auto-generated method stub
		String param = "?mcc=" + mcc + "&mnc=" + mnc 
				+ "&cells=" + lbsInfo.substring(0, lbsInfo.length() - 1) 
				+ "&wifi="+ "&key=9KD84JGH382JF1O";
		String ret = connectURL(LBS_WIFI_URL + param, "");
		
		System.out.println("ret = " + ret);
		
		String[] gps = ret.split(",");
		
		return gps[0] + "," + gps[1];
	}
	
	public static String gpsCoverLbsWifi(int mcc, int mnc, String lbsInfo, String wifiInfo) {
		// TODO Auto-generated method stub
		String param = "?mcc=" + mcc + "&mnc=" + mnc 
				+ "&cells=" + lbsInfo.substring(0, lbsInfo.length() - 1) 
				+ "&wifi=" + wifiInfo.substring(0, wifiInfo.length() - 1) 
				+ "&key=9KD84JGH382JF1O";
		String ret = connectURL(LBS_WIFI_URL + param, "");
		
		System.out.println("ret = " + ret);
		
		String[] gps = ret.split(",");
		
		return gps[0] + "," + gps[1];
	}
}